package com.example.monitoring.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;

public class JvmMonitor {

    private final RestTemplate restTemplate = new RestTemplate();
    private final String jolokiaUrl = "http://127.0.0.1:9999/omms/actuator/jolokia";
    private final String credentials = "admin:123456";
    private final String encodedCredentials = Base64Utils.encodeToString(credentials.getBytes());

    public static void main(String[] args) {
        JvmMonitor jvmMonitor = new JvmMonitor();
        System.out.println(jvmMonitor.getHeapMemoryUsage());
        System.out.println(jvmMonitor.getThreadCount());
    }

    // 获取 JVM 堆内存使用情况
    public String getHeapMemoryUsage() {
        String payload = "{\"type\":\"read\",\"mbean\":\"java.lang:type=Memory\",\"attribute\":\"HeapMemoryUsage\"}";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Basic " + encodedCredentials);  // 添加认证头

        HttpEntity<String> request = new HttpEntity<>(payload, headers);

        return restTemplate.postForObject(jolokiaUrl, request, String.class);
    }

    // 获取线程信息
    public String getThreadCount() {
        String payload = "{\"type\":\"read\",\"mbean\":\"java.lang:type=Threading\",\"attribute\":\"ThreadCount\"}";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Basic " + encodedCredentials);  // 添加认证头

        HttpEntity<String> request = new HttpEntity<>(payload, headers);

        return restTemplate.postForObject(jolokiaUrl, request, String.class);
    }
}